package com.example.s.Activity.team;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.example.s.Activity.BaseActivity;
import com.example.s.R;
import com.example.s.adapter.InnerHolder;
import com.example.s.adapter.MyRecyclerViewAdapter;
import com.example.s.utils.LiveDataBus;
import com.example.s.utils.MyUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class CreateTeamActivity extends BaseActivity {
    private ImageView back;
    private TextView release;
    private EditText content;
    private TextView maxSize;
    private RecyclerView photoRv;
    private TextView activityTime;
    private TextView goOffTime;
    private TextView goOffPlace;
    private TextView destination;
    private EditText EditAttention;
    private LinearLayout contentContainer;
    private RelativeLayout activityTimeContainer;
    private RelativeLayout goOffTimeContainer;
    private RelativeLayout goOffPlaceContainer;
    private RelativeLayout destinationContainer;


    private List<Uri> photoList = new ArrayList<>();
    private MyRecyclerViewAdapter<Uri> mPhotoAdapter;


    private void initView() {

        activityTimeContainer = (RelativeLayout) findViewById(R.id.activityTimeContainer);
        goOffTimeContainer = (RelativeLayout) findViewById(R.id.goOffTimeContainer);
        goOffPlaceContainer = (RelativeLayout) findViewById(R.id.goOffPlaceContainer);
        destinationContainer = (RelativeLayout) findViewById(R.id.destinationContainer);

        back = (ImageView) findViewById(R.id.back);
        release = (TextView) findViewById(R.id.release);
        content = (EditText) findViewById(R.id.content);
        maxSize = (TextView) findViewById(R.id.maxSize);
        photoRv = (RecyclerView) findViewById(R.id.photoRv);
        activityTime = (TextView) findViewById(R.id.activityTime);
        goOffTime = (TextView) findViewById(R.id.goOffTime);
        goOffPlace = (TextView) findViewById(R.id.goOffPlace);
        destination = (TextView) findViewById(R.id.destination);
        EditAttention = (EditText) findViewById(R.id.EditAttention);
        contentContainer = (LinearLayout) findViewById(R.id.contentContainer);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_create_team);
        initView();
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        restrictNum();

        setPhotoAdapter();

        loadDatePicker();

        loadTimePicker();
    }

    private void loadTimePicker() {
        goOffTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TimePickerView pvTime = new TimePickerBuilder(CreateTeamActivity.this, new OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {
                        goOffTime.setText(MyUtils.getInstance().getDateString(date,true));
                    }

                }).setBgColor(Color.parseColor("#000000"))
                        .setTitleBgColor(Color.parseColor("#0a0a0a"))
                        .setTextColorCenter(Color.parseColor("#ffffff"))
                        .setTextColorOut(Color.parseColor("#575757"))
                        .setDividerColor(Color.parseColor("#1c1c27"))
                        .setSubmitColor(0xFFF5F6FA)
                        .setCancelColor(0xFFF5F6FA)
                        .setCancelText("取消")//取消按钮文字
                        .setSubmitText("确定")//确认按钮文字
                        .isCenterLabel(false)
                        .setType(new boolean[]{false, false, false, true, true, false})// 小时，分钟
                        .build();
                pvTime.show();
            }
        });
    }

    private void loadDatePicker() {
        activityTimeContainer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TimePickerView pvTime = new TimePickerBuilder(CreateTeamActivity.this, new OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {
                        activityTime.setText(MyUtils.getInstance().getDateString(date));
                    }

                }).setBgColor(Color.parseColor("#000000"))
                        .setTitleBgColor(Color.parseColor("#0a0a0a"))
                        .setTextColorCenter(Color.parseColor("#ffffff"))
                        .setTextColorOut(Color.parseColor("#575757"))
                        .setDividerColor(Color.parseColor("#1c1c27"))
                        .setSubmitColor(0xFFF5F6FA)
                        .setCancelColor(0xFFF5F6FA)
                        .setCancelText("取消")//取消按钮文字
                        .setSubmitText("确定")//确认按钮文字
                        .isCenterLabel(false)
                        .setType(new boolean[]{true, true, true, false, false, false})// 默认全部显示
                        .build();
                pvTime.show();
            }
        });
    }

    private void restrictNum() {
        content.setFilters(new InputFilter[]{new InputFilter.LengthFilter(300)});
        content.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                maxSize.setText(s.length() + "/300");
            }
        });
    }

    private void setPhotoAdapter() {
        photoList.add(null);
        contentContainer.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
            @Override
            public void onGlobalLayout() {
                int width = contentContainer.getWidth();
                int px = MyUtils.getInstance().dip2px(CreateTeamActivity.this, 20);
                int realWidth = (width - px) / 3;
                LiveDataBus.getInstance().with("photoRealWidth", Integer.class).setValue(realWidth);
                Log.d(TAG, "onGlobalLayout: " + realWidth);
                contentContainer.getViewTreeObserver().removeOnGlobalLayoutListener(this);
            }
        });

        photoRv.setLayoutManager(new GridLayoutManager(CreateTeamActivity.this, 3));
        photoRv.setAdapter(mPhotoAdapter = new MyRecyclerViewAdapter<Uri>(photoList, R.layout.rv_upload_photo_item) {
            @Override
            public void handleData(InnerHolder holder, Uri item) {
                ImageView cover = holder.getView(R.id.cover);
                LiveDataBus.getInstance().with("photoRealWidth", Integer.class).observe(CreateTeamActivity.this, new Observer<Integer>() {
                    @Override
                    public void onChanged(Integer integer) {
                        if (integer != null) {
                            FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) cover.getLayoutParams();
                            layoutParams.width = integer;
                            layoutParams.height = integer;
                            cover.setLayoutParams(layoutParams);
                        }
                    }
                });

                ImageView add = holder.getView(R.id.add_bg);
                add.setVisibility(View.GONE);
                if (item != null) {
                    cover.setImageURI(item);
                }
                cover.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (holder.getAdapterPosition() >= photoList.size() - 1) {
                            Intent intent = new Intent(Intent.ACTION_PICK, null);
                            intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                            startActivityForResult(intent, 2);
                        }
                    }
                });

                if (holder.getAdapterPosition() >= photoList.size() - 1) {
                    cover.setImageResource(R.mipmap.upload_add_bg);
                    cover.setScaleType(ImageView.ScaleType.CENTER_CROP);
                    add.setVisibility(View.VISIBLE);
                    add.setBackgroundResource(R.mipmap.upload_add);

                }
                Log.d(TAG, "handleData: " + holder.getAdapterPosition());
                Log.d(TAG, "handleData: " + holder.getLayoutPosition());
            }

        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 2 && resultCode == RESULT_OK && data != null) {
            Uri uri = data.getData();
            photoList.add(0, uri);
            mPhotoAdapter.notifyDataSetChanged();
        }
    }
}
